package com.boarsoft.message.store.jdbc.mysql;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.message.bean.MessageEntity;
import com.boarsoft.message.bean.MessageQueryParam;
import com.boarsoft.message.store.jdbc.JdbcUtil;
import com.boarsoft.message.store.jdbc.MsgJdbcRoller;
import com.boarsoft.message.store.jdbc.MsgMainTM;
import com.boarsoft.serialize.HessianSerializer;
import com.boarsoft.serialize.ObjectSerializer;

/**
 * 基于MySQL的消息存储器，通过操作两张表来完成消息及其收件人收发状态的保存和更新<br>
 * 它是用针对Mysql的TableMapping来完成数据库操作的。
 * 
 * @author Mac_J
 *
 */
public class MsgMySqlRoller extends MsgJdbcRoller {
	private static final Logger log = LoggerFactory.getLogger(MsgMySqlRoller.class);

	/** 查询时的分页大小（用于从数据表中恢复数据，一次从表中查询的消息数） */
	protected int pageSize = 200;
	/** 消息存储（在字段中的）的格式 */
	protected short type = MsgMainTM.TYPE_JSON;
	/** 对象序列化器，type=TYPE_BLOB 时有效 */
	protected ObjectSerializer serializer = new HessianSerializer();

	public void init() throws Exception {
		mainTm = new MsgMysqlMainTM(target);
		mainTm.setPageSize(pageSize);
		mainTm.setType(type);
		mainTm.setSerializer(serializer);
		mainTm.init();
		detailTm = new MsgMysqlDetailTM(target);
		detailTm.init();
		super.init();
	}

	@Override
	public List<MessageEntity> query(MessageQueryParam param) {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return mainTm.list(conn, param);
		} catch (Exception e) {
			log.error("query message param: {} error:{} ", param.toString(), e);
			return new ArrayList<>();
		} finally {
			JdbcUtil.close(conn);
		}
	}

	@Override
	public List<Map<String, Object>> count(MessageQueryParam param) {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return mainTm.count(conn, param);
		} catch (Exception e) {
			log.error("count message param: {} error:{} ", param.toString(), e);
			return new ArrayList<>();
		} finally {
			JdbcUtil.close(conn);
		}
	}

	@Override
	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public short getType() {
		return type;
	}

	public void setType(short type) {
		this.type = type;
	}

	public ObjectSerializer getSerializer() {
		return serializer;
	}

	public void setSerializer(ObjectSerializer serializer) {
		this.serializer = serializer;
	}
}